package com.hxs.learn.action.core;

import javax.servlet.http.HttpServletRequest;

import com.hxs.learn.constants.core.web.ReqConst;
import com.hxs.learn.constants.core.web.view.ViewNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import com.hxs.learn.common.exception.ServiceException;
import com.hxs.learn.common.web.HttpContext;
import com.hxs.learn.common.web.LoginInfo;
import com.hxs.learn.entity.core.SysMenu;
import com.hxs.learn.service.core.SysMenuService;

/**
 * @author kevin
 */
public abstract class AbstractViewAction {
    protected static final String CURR_USER = "user";
    protected static final String PAGE_DATA = "data";
    protected static final String   PAGE_DATA_LIST = "dataList";
    protected static final String PAGE_REDIRECT = "redirect:";
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    SysMenuService menuService;

    public AbstractViewAction() {
    }

    protected ModelAndView createModelAndView(LoginInfo userInfo) {
        return createModelAndView(new ModelAndView(), userInfo);
    }

    protected ModelAndView createModelAndView(ModelAndView mv) {
        mv.addObject(ReqConst.PARAM_HOST, HttpContext.getUrlRoot());
        return mv;
    }

    protected ModelAndView createModelAndView(String viewName) {
        return createModelAndView(new ModelAndView(viewName));
    }

    protected ModelAndView createModelAndView(ModelAndView mv, LoginInfo userInfo) {
        HttpServletRequest request = HttpContext.getRequest();
        String contextPath = request.getContextPath();
        String path = request.getRequestURI();

        if (contextPath.length() > 0) {
            path = path.substring(contextPath.length());
        }

        path = path.replaceFirst("/", "");

        SysMenu menu = menuService.findByUrl(path);

        if (menu == null) {
            throw new ServiceException(404, "菜单Url不存在，请到数据库t_sys_menu表添加菜单");
        }

        String viewName = menu.getView();

        viewName = ViewNames.PREFIX + viewName;
        mv.setViewName(viewName);

        return createModelAndView(mv);
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
